package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.api.common.LineUtil;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.ActivityTarget;
import com.ybkj.daijia.server.sales.Activity.ActivityType;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.ActivityRecord;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.ActivityService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.MemberNoticeService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuanxian.Line;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private MemberNoticeService memberNoticeService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private ZhuanxianService zhuanxianService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(
        @RequestParam(required = true, value = "event") String event,
        @RequestParam(required = false, value = "type") String type
    ) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("activity")) {
            ModelAndView mv = new ModelAndView();
            if (event.equals("adminGift")) {
                mv.addObject("coupons", couponRuleService.listValid());
                mv.addObject("companys", companyService.findAll());
                mv.addObject("grades", memberService.listAllGrades());
                mv.setViewName("activity/addadmingift");
            } else {
                mv.setViewName("activity/list");
            }
            mv.addObject("event", event);
            mv.addObject("type", type);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "listData", method = RequestMethod.GET)
    public @ResponseBody
    Page<Activity> listData(
        @RequestParam(required = true, value = "event") String event,
        @RequestParam(required = false, value = "type") String type) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("activity")) {
            if (type.isEmpty()) {
                type = null;
            }

            Page<Activity> result = activityService.queryActivities(event, type);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "giftCoupon", method = RequestMethod.POST)
    public @ResponseBody
    Result<Coupon> giftCoupon(
        @RequestParam(required = false, value = "content") String content,
        @RequestParam(required = false, value = "carNumber") String carNumber,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "companyIds") Long[] companyIds,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "gradeIds") Long gradeIds[],
        @RequestParam(required = false, value = "type") Integer type[],
        @RequestParam(required = false, value = "allowOverdraw") Boolean[] allowOverdraw,
        @RequestParam(required = false, value = "overDay") Integer overDay,
        @RequestParam(required = false, value = "orderType") OrderType orderType,
        @RequestParam(required = false, value = "messageType") String[] messageType,
        @RequestParam(required = true, value = "couponRuleId") String couponRuleId,
        @RequestParam(required = true, value = "amount") String amount) {

        Subject subject = SecurityUtils.getSubject();

        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        if (subject.isPermitted("activity")) {
            String sendTypes = "";
            for (String st : messageType) {
                sendTypes += st + ",";
            }
            result = couponService
                .giftCoupon(content, carNumber, name, phone, companyIds, startTime, endTime,
                    gradeIds, type, allowOverdraw, overDay, orderType, sendTypes, couponRuleId,
                    amount);

            return result;

        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("activity")) {
            ModelAndView mv = new ModelAndView();

            Activity activity = activityService.findOne(id);
            mv.addObject("activity", activity);
            mv.addObject("companys", companyService.findAll());
            mv.addObject("grades", memberService.listAllGrades());

            if (activity.getActivityEvent().equals(ActivityEvent.newRegister)) {
                mv.setViewName("activity/editnewregister");
            } else if (activity.getActivityEvent().equals(ActivityEvent.phoneGift)) {
                mv.setViewName("activity/editphonegift");
            } else if (activity.getActivityEvent().equals(ActivityEvent.shareSuccess)) {
                mv.setViewName("activity/editsharesuccess");
            } else if (activity.getActivityEvent().equals(ActivityEvent.invite)) {
                mv.setViewName("activity/editinvite");
            } else if (activity.getActivityEvent().equals(ActivityEvent.orderCompleteTimes)) {
                mv.setViewName("activity/editordercompletetimes");
            } else if (activity.getActivityEvent().equals(ActivityEvent.firstOrderFree)) {
                mv.setViewName("activity/editfirstorderfree");
            } else if (activity.getActivityEvent().equals(ActivityEvent.recharging)) {
                mv.setViewName("activity/editrecharging");
            } else if (activity.getActivityEvent().equals(ActivityEvent.lineCoupon)) {
                mv.setViewName("activity/editLineCoupon");
            }

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("activity")) {
            ModelAndView mv = new ModelAndView();

            Activity activity = activityService.findOne(id);
            mv.addObject("activity", activity);
            Integer page2 = Pager.getPage();
            Integer rows = Pager.getLimit();
            Page<ActivityRecord> page = activityService
                .queryActivityRecord(activity.getId(), phone, companyId, startTime, endTime, page2,
                    rows);
            Page<ActivityRecord> pageAll = activityService
                .queryActivityRecord(activity.getId(), phone, companyId, startTime, endTime, null,
                    null);
            List<ActivityRecord> list = pageAll.getContent();
            int sum = 0;
            int sumAll = 0;
            for (ActivityRecord activityRecord : list) {
                if (StringUtils.isNotBlank(activity.getActivityType().toString())) {
                    if (activity.getActivityType().equals(Activity.ActivityType.cash)) {
                        if (activityRecord.getMoney() != null) {
                            sum = sum + activityRecord.getMoney().intValue();
                        }

                        mv.addObject("sum", sum);
                    } else if (activity.getActivityType().equals(Activity.ActivityType.coupon)) {
                        int sumAmounts = 0;
                        if (activityRecord.getLingquAmounts() != null) {
                            String[] strings = activityRecord.getLingquAmounts().split(",");
                            for (String string : strings) {
                                if (StringUtils.isNotBlank(string)) {
                                    sumAmounts = sumAmounts + Integer.parseInt(string);
                                }
                            }
                            sumAll = sumAll + sumAmounts;
                        }
                        mv.addObject("sumAll", sumAll);
                    }
                }

            }
            mv.addObject("passengerAll", activityService
                .countActivityRecord(activity.getId(), phone, companyId, startTime, endTime));
            mv.addObject("companys", companyService.findAll());
            mv.addObject("phone", phone);
            mv.addObject("companyId", companyId);
            mv.addObject("startTime", startTime);
            mv.addObject("endTime", endTime);

            mv.addObject("page", page);

            mv.setViewName("activity/detail");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(
        @RequestParam(required = true, value = "event") String event,
        @RequestParam(required = false, value = "type") String type
    ) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("activity")) {
            ModelAndView mv = new ModelAndView();
            List<CouponRule> list = couponRuleService.listValid();
            //数量太多 先注释掉
//			List<CouponRule> list2 = new ArrayList<CouponRule>();
//			for (CouponRule couponRule : list) {
//				List<Coupon> list3 = couponService.findAll(couponRule.getId());
//				if(couponRule.getNumber()>list3.size()){
//					list2.add(couponRule);
//				}
//			}

            mv.addObject("coupons", list);
            mv.addObject("companys", companyService.findAll());
            mv.addObject("grades", memberService.listAllGrades());
            mv.addObject("type", type);
            //添加线路数据
            List<Line> lineList = zhuanxianService.queryLines(principal.getCompanyId());
            lineList = LineUtil.deleteRepreat(lineList);
            mv.addObject("lines", lineList);

            if (event.equals(ActivityEvent.newRegister.toString())) {
                mv.setViewName("activity/addnewregister");
            } else if (event.equals(ActivityEvent.phoneGift.toString())) {
                mv.setViewName("activity/addphonegift");
            } else if (event.equals(ActivityEvent.shareSuccess.toString())) {
                mv.setViewName("activity/addsharesuccess");
            } else if (event.equals(ActivityEvent.invite.toString())) {
                mv.setViewName("activity/addinvite");
            } else if (event.equals(ActivityEvent.orderCompleteTimes.toString())) {
                mv.setViewName("activity/addordercompletetimes");
            } else if (event.equals(ActivityEvent.firstOrderFree.toString())) {
                mv.setViewName("activity/addfirstorderfree");
            } else if (event.equals(ActivityEvent.recharging.toString())) {
                mv.setViewName("activity/addrecharging");
            } else if (event.equals(ActivityEvent.lineCoupon.toString())) {
                mv.setViewName("activity/addLineCoupon");
            } else if (event.equals(ActivityEvent.zhuancheCoupon.toString())) {
                mv.setViewName("activity/addZhuancheCoupon");
            } else if (event.equals(ActivityEvent.reviewCoupon.toString())) {
                mv.setViewName("activity/addReviewCoupon");
            }

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * @param activityEvent       事件名称
     * @param companyIds          公司ID
     * @param companyNames        公司名称
     * @param activityTarget      客户类型
     * @param gradeIds            客户等级
     * @param gradeNames          等级名称
     * @param sharePlatforms
     * @param sharePlatformNames
     * @param shareTimes
     * @param restriction
     * @param passengerFromSource 注册渠道
     * @param orderFromSource
     * @param completeTimes
     * @param orderType
     * @param activityType        活动类型
     * @param money               返现金额
     * @param couponIds           优惠券id
     * @param couponAmounts       优惠券数量
     * @param start               活动开始时间
     * @param end                 活动结束时间
     * @param messageType         通知方式
     * @param backgroudColor
     * @param activityContent
     * @param freeType
     * @param otherMoney
     * @param rechargingMoney
     * @param imgsUrl
     * @param activityRange       订单类型
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Activity> create(
        @RequestParam(value = "activityEvent") ActivityEvent activityEvent,
        @RequestParam(value = "start") String start,
        @RequestParam(required = false, value = "companyIds") String companyIds,
        @RequestParam(required = false, value = "companyNames") String companyNames,
        @RequestParam(required = false, value = "activityTarget") ActivityTarget activityTarget,
        @RequestParam(required = false, value = "gradeIds") String gradeIds,
        @RequestParam(required = false, value = "gradeNames") String gradeNames,
        @RequestParam(required = false, value = "sharePlatforms") String sharePlatforms,
        @RequestParam(required = false, value = "sharePlatformNames") String sharePlatformNames,
        @RequestParam(required = false, value = "shareTimes") Integer shareTimes,
        @RequestParam(required = false, value = "restriction") Integer restriction,
        @RequestParam(required = false, value = "passengerFromSource") String passengerFromSource,
        @RequestParam(required = false, value = "orderFromSource") String orderFromSource,
        @RequestParam(required = false, value = "completeTimes") Integer completeTimes,
        @RequestParam(required = false, value = "orderType") OrderType orderType,
        @RequestParam(required = false, value = "activityType") ActivityType activityType,
        @RequestParam(required = false, value = "money") BigDecimal money,
        @RequestParam(required = false, value = "couponIds") String couponIds,
        @RequestParam(required = false, value = "couponAmounts") String couponAmounts,
        @RequestParam(required = false, value = "end") String end,
        @RequestParam(required = false, value = "messageType") String messageType,
        @RequestParam(required = false, value = "backgroudColor") String backgroudColor,
        @RequestParam(required = false, value = "activityContent") String activityContent,
        @RequestParam(required = false, value = "freeType") Integer freeType,
        @RequestParam(required = false, value = "otherMoney") BigDecimal otherMoney,
        @RequestParam(required = false, value = "rechargingMoney") BigDecimal rechargingMoney,
        @RequestParam(required = false, value = "imgsUrl") String imgsUrl,
        @RequestParam(required = false, value = "lineId") Long lineId,
        @RequestParam(required = false, value = "lineName") String lineName,
        @RequestParam(required = false, value = "reviewGrade") Integer reviewGrade,
        @RequestParam(required = false, value = "activityRange") String activityRange)
        throws ParseException {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("activity")) {

            Activity activity = new Activity();
            if (null != lineId) {
                activity.setLineId(lineId);
            }
            if (null != lineName) {
                activity.setLineName(lineName);
            }
            activity.setActivityRange(activityRange);
            activity.setActivityEvent(activityEvent);
            activity.setActivityTarget(activityTarget);
            activity.setActivityType(activityType);
            activity.setGradeIds(gradeIds);
            activity.setGradeNames(gradeNames);
            activity.setPassengerFromSource(passengerFromSource);
            activity.setReviewGrade(reviewGrade);

            if (null != activityType) {
                if (activityType.equals(Activity.ActivityType.cash)) {
                    activity.setMoney(money);
                } else if (activityType.equals(Activity.ActivityType.coupon)) {
                    activity.setCouponIds(couponIds);
                    activity.setCouponAmounts(couponAmounts);
                }
            }

            if (principal.isCompanyType()) {
                activity.setCompanyIds(companyIds);
                activity.setCompanyNames(companyNames);
            } else {
                activity.setCompanyIds(principal.getCompanyId().toString());
                activity.setCompanyNames(principal.getCompanyAbbreviation());
            }
            activity.setStart(DateUtils.parseDate(start, "yyyy-MM-dd").getTime());
            if (StringUtils.isNotBlank(end)) {
                activity.setEnd(DateUtils.parseDate(end, "yyyy-MM-dd").getTime());
            }

            //分享成功相关
            activity.setSharePlatforms(sharePlatforms);
            activity.setSharePlatformNames(sharePlatformNames);
            activity.setShareTimes(shareTimes);
            activity.setRestriction(restriction);

            //完成订单相关
            activity.setOrderFromSource(orderFromSource);
            activity.setCompleteTimes(completeTimes);
            activity.setOrderType(orderType);

            //根据手机号赠送优惠券
            activity.setBackgroudColor(backgroudColor);
            activity.setActivityImage(imgsUrl);
            activity.setActivityContent(activityContent);

            //充值满相关
            activity.setRechargingMoney(rechargingMoney);

            //首单免费相关
            activity.setFreeType(freeType);

            activity.setMessageType(messageType);
            try {
                if (activityEvent == ActivityEvent.firstOrderFree) {
                    Page<Activity> activities = activityService
                        .queryActivities(String.valueOf(ActivityEvent.firstOrderFree), null);
                    List<Activity> list = activities.getContent();
                    if (!CollectionUtils.isEmpty(list)) {

                        for (Activity activity2 : list) {

                            String companyIds2 = activity2.getCompanyIds();
                            String gradeIds2 = activity2.getGradeIds();
                            String fromSources = activity2.getOrderFromSource();
                            String[] companyId = companyIds.split(",");
                            String[] companyId2 = companyIds2.split(",");
                            String[] gradeId = gradeIds.split(",");
                            String[] gradeId2 = gradeIds2.split(",");
                            String[] fromSource = orderFromSource.split(",");
                            String[] fromSource2 = fromSources.split(",");
                            if (!end.isEmpty()) {
                                if (DateUtils.parseDate(end, "yyyy-MM-dd").getTime() < new Date()
                                    .getTime()) {
                                    for (int i = 0; i < companyId.length; i++) {
                                        for (int i2 = 0; i2 < companyId2.length; i2++) {
                                            for (int j = 0; j < gradeId.length; j++) {
                                                for (int j2 = 0; j2 < gradeId2.length; j2++) {
                                                    for (int k = 0; k < fromSource.length; k++) {
                                                        for (int k2 = 0; k2 < fromSource2.length;
                                                            k2++) {
                                                            if (companyId[i].equals(companyId2[i2])
                                                                && gradeId[j].equals(gradeId2[j2])
                                                                && fromSource[k]
                                                                .equals(fromSource2[k2]) &&
                                                                activity2.getOrderType()
                                                                    .equals(orderType) &&
                                                                (activity2.getActivityTarget()
                                                                    .equals(ActivityTarget.all)
                                                                    || activity2.getActivityTarget()
                                                                    .equals(activityTarget))) {
                                                                throw new RuntimeException(
                                                                    "首单免费活动相同类型只能创建一个！");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                for (int i = 0; i < companyId.length; i++) {
                                    for (int i2 = 0; i2 < companyId2.length; i2++) {
                                        for (int j = 0; j < gradeId.length; j++) {
                                            for (int j2 = 0; j2 < gradeId2.length; j2++) {
                                                for (int k = 0; k < fromSource.length; k++) {
                                                    for (int k2 = 0; k2 < fromSource2.length;
                                                        k2++) {
                                                        if (companyId[i].equals(companyId2[i2])
                                                            && gradeId[j].equals(gradeId2[j2])
                                                            && fromSource[k].equals(fromSource2[k2])
                                                            &&
                                                            activity2.getOrderType()
                                                                .equals(orderType) && (
                                                            activity2.getActivityTarget()
                                                                .equals(ActivityTarget.all)
                                                                || activity2.getActivityTarget()
                                                                .equals(activityTarget))) {
                                                            throw new RuntimeException(
                                                                "首单免费活动相同类型只能创建一个！");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                result = activityService.create(activity);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setMessage("首单免费活动相同类型只能创建一个！");
            }

            if (result.isSuccess()) {
                String detail = "【%s】新增了活动【" + activity.getActivityEventName() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public @ResponseBody
    Result<Activity> update(
        @RequestParam(required = true, value = "id") Long id,
        @RequestParam(required = false, value = "companyIds") String companyIds,
        @RequestParam(required = false, value = "companyNames") String companyNames,
        @RequestParam(required = false, value = "activityTarget") ActivityTarget activityTarget,
        @RequestParam(required = false, value = "gradeIds") String gradeIds,
        @RequestParam(required = false, value = "gradeNames") String gradeNames,
        @RequestParam(required = false, value = "sharePlatforms") String sharePlatforms,
        @RequestParam(required = false, value = "sharePlatformNames") String sharePlatformNames,
        @RequestParam(required = false, value = "passengerFromSource") String passengerFromSource,
        @RequestParam(required = false, value = "orderFromSource") String orderFromSource,
        @RequestParam(required = false, value = "end") String end,
        @RequestParam(required = false, value = "messageType") String messageType,
        @RequestParam(required = false, value = "backgroudColor") String backgroudColor,
        @RequestParam(required = false, value = "activityContent") String activityContent,
        @RequestParam(required = false, value = "imgsUrl") String imgsUrl) throws ParseException {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("activity")) {

            Activity activity = new Activity();
            activity.setId(id);
            activity.setActivityTarget(activityTarget);
            activity.setGradeIds(gradeIds);
            activity.setGradeNames(gradeNames);
            activity.setPassengerFromSource(passengerFromSource);

            if (principal.isCompanyType()) {
                activity.setCompanyIds(companyIds);
                activity.setCompanyNames(companyNames);
            } else {
                activity.setCompanyIds(principal.getCompanyId().toString());
                activity.setCompanyNames(principal.getCompanyAbbreviation());
            }
            if (StringUtils.isNotBlank(end)) {
                activity.setEnd(DateUtils.parseDate(end, "yyyy-MM-dd").getTime());
            }

            //分享成功相关
            activity.setSharePlatforms(sharePlatforms);
            activity.setSharePlatformNames(sharePlatformNames);

            //完成订单相关
            activity.setOrderFromSource(orderFromSource);

            //根据手机号赠送优惠券
            activity.setBackgroudColor(backgroudColor);
            activity.setActivityImage(imgsUrl);
            activity.setActivityContent(activityContent);

            activity.setMessageType(messageType);
            Activity activity3 = activityService.findOne(id);
            try {
                if (activity3.getActivityEvent() == ActivityEvent.firstOrderFree) {
                    Page<Activity> activities = activityService
                        .queryActivities(String.valueOf(ActivityEvent.firstOrderFree), null);
                    List<Activity> list = activities.getContent();
                    for (Activity activity2 : list) {
                        if (!activity2.getId().equals(id)) {

                            String companyIds2 = activity2.getCompanyIds();
                            String gradeIds2 = activity2.getGradeIds();
                            String fromSources = activity2.getOrderFromSource();
                            String[] companyId = companyIds.split(",");
                            String[] companyId2 = companyIds2.split(",");
                            String[] gradeId = gradeIds.split(",");
                            String[] gradeId2 = gradeIds2.split(",");
                            String[] fromSource = orderFromSource.split(",");
                            String[] fromSource2 = fromSources.split(",");
                            if (!end.isEmpty()) {
                                if (DateUtils.parseDate(end, "yyyy-MM-dd").getTime() > new Date()
                                    .getTime()) {
                                    for (int i = 0; i < companyId.length; i++) {
                                        for (int i2 = 0; i2 < companyId2.length; i2++) {
                                            for (int j = 0; j < gradeId.length; j++) {
                                                for (int j2 = 0; j2 < gradeId2.length; j2++) {
                                                    for (int k = 0; k < fromSource.length; k++) {
                                                        for (int k2 = 0; k2 < fromSource2.length;
                                                            k2++) {
                                                            if (companyId[i].equals(companyId2[i2])
                                                                && gradeId[j].equals(gradeId2[j2])
                                                                && fromSource[k]
                                                                .equals(fromSource2[k2]) &&
                                                                (activityTarget
                                                                    .equals(ActivityTarget.all)
                                                                    || activity2.getActivityTarget()
                                                                    .equals(activityTarget))) {
                                                                throw new RuntimeException(
                                                                    "首单免费活动相同类型只能创建一个！");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                for (int i = 0; i < companyId.length; i++) {
                                    for (int i2 = 0; i2 < companyId2.length; i2++) {
                                        for (int j = 0; j < gradeId.length; j++) {
                                            for (int j2 = 0; j2 < gradeId2.length; j2++) {
                                                for (int k = 0; k < fromSource.length; k++) {
                                                    for (int k2 = 0; k2 < fromSource2.length;
                                                        k2++) {
                                                        if (companyId[i].equals(companyId2[i2])
                                                            && gradeId[j].equals(gradeId2[j2])
                                                            && fromSource[k].equals(fromSource2[k2])
                                                            &&
                                                            (activityTarget
                                                                .equals(ActivityTarget.all)
                                                                || activity2.getActivityTarget()
                                                                .equals(activityTarget))) {
                                                            throw new RuntimeException(
                                                                "首单免费活动相同类型只能创建一个！");
                                                        }

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }

                }
                result = activityService.update(activity);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setMessage("首单免费活动相同类型只能创建一个！");
            }

            if (result.isSuccess()) {
                String detail = "【%s】修改了活动【" + activity.getActivityEventName() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }


    @RequestMapping(value = "stop", method = RequestMethod.POST)
    public @ResponseBody
    Result<Activity> stop(Long activityId, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        if (subject.isPermitted("activity")) {

            if (null != activityId) {
                Activity activity = activityService.findOne(activityId);
                if (null != activity) {
                    result = activityService.stop(activity.getId());

                    String detail = "【%s】停止了活动【" + activity.getActivityEventName() + "】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("操作成功");
                } else {
                    result.setMessage("没有可以操作的数据");
                }
            } else {
                result.setMessage("没有可以操作的数据");
            }

        } else {
            result.setMessage("您没有该权限");
        }

        return result;

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Activity> delete(Long activityId, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        if (subject.isPermitted("activity")) {

            if (null != activityId) {
                Activity activity = activityService.findOne(activityId);
                if (null != activity) {
                    result = activityService.delete(activity.getId());

                    String detail = "【%s】删除了活动【" + activity.getActivityEventName() + "】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("操作成功");
                } else {
                    result.setMessage("没有可以操作的数据");
                }
            } else {
                result.setMessage("没有可以操作的数据");
            }

        } else {
            result.setMessage("您没有该权限");
        }

        return result;

    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

